<template lang="html">
  <div class="platform-user-add">
    <nav-header>
      <template slot="menuBefore">
        <li><router-link to="/user/user/platform-user" tag="a">平台用户管理</router-link></li>
        <li class="gap">&gt;</li>
      </template>
    </nav-header>

    <el-form ref="addForm" :model="addForm" status-icon label-position="left" :rules="rules" label-width="80px"
      class="add-form" v-loading="loading.status" :element-loading-text="loading.txt">
      <p class="form-title">基本信息</p>
      <el-form-item label="用户名" prop="name" class="edit-from-width">
        <el-input v-model.trim="addForm.name" placeholder="请输入真实姓名" autocomplete="off" :maxlength="parseInt(20)"
          clearable>
        </el-input>
      </el-form-item>
      <el-form-item label="人脸照片" prop="faceImg" class="edit-from-width">
        <upload-img :options="uploadOptions" :picture="addForm.face_path" @imgListen="getImg"></upload-img>
      </el-form-item>
      <el-form-item label="性别">
        <el-radio v-model="addForm.sex" label="1">男</el-radio>
        <el-radio v-model="addForm.sex" label="2">女</el-radio>
      </el-form-item>
      <el-form-item label="组织架构" class="edit-from-width">
        <el-select v-model="addForm.org_id" filterable placeholder="请填写组织架构" :disabled="true">
          <el-option v-for="val in orgData" :key="val.id" :label="val.name" :value="val.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="角色权限" prop="role_id">
        <el-checkbox-group v-model="addForm.role_id" @change="addFormRoleChange">
          <template v-for="item in roleData">
            <el-checkbox v-if="parseInt(item.id) > 0" :label="item.base_id === 0 ? item.id : item.base_id"
              :key="item.id" border>{{ item.name }}</el-checkbox>
          </template>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="登录账号" prop="number" class="edit-from-width">
        <el-input v-model="addForm.number" placeholder="登录时要想到的账号" autocomplete="off" :maxlength="parseInt(16)"
          clearable>
        </el-input>
      </el-form-item>

      <el-form-item label="设置密码" prop="password" class="edit-from-width">
        <el-input v-model="addForm.password" type="password" placeholder="默认密码为Admin@1993；输入可更新密码"
          :maxlength="parseInt(16)" show-password clearable></el-input>
        <span style="margin-left:10px; font-size:14px; color: #409eff;">未设置密码时使用默认密码</span>
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPwd" class="edit-from-width">
        <el-input v-model="confirmPwd" type="password" clearable placeholder="再次输入新密码" :maxlength="parseInt(16)"
          show-password></el-input>
      </el-form-item>
      <el-form-item v-if="isShowSubjectFlag" label="任教科目" class="edit-from-width">
        <el-select v-model="addForm.subject_id" filterable placeholder="选择任教科目">
          <el-option v-for="val in subjectData" :key="val.id" :label="val.name" :value="val.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="$g.user_id === $g.GLOBE_ADMIN_ID" prop="user_time" class="user-time" label="有效时间">
        <el-radio-group v-model="user_time">
          <el-radio label="1">永久有效</el-radio>
          <el-radio label="2">
            <div>
              <span>临时用户</span>
              <span style="margin-left: 20px;">使用截止时间：
                <el-date-picker :picker-options="pickerOptions" v-model="short_time" type="datetime"
                  placeholder="选择日期时间" value-format="yyyy-MM-dd HH:mm:ss">
                </el-date-picker>
              </span>
            </div>
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <div v-if="isParent">
        <p class="form-title">角色设定（家长）</p>
        <div class="children-box">
          <el-tabs v-model="parentEditTabsValue" type="card" editable @edit="parentHandleTabsEdit"
            :class="addForm.parent_bind.length < 10 ? 'tabs-head-title' : ''">
            <el-tab-pane v-for="(item, index) in addForm.parent_bind"
              :label="item.childrenName ? item.childrenName : '子女' + (index + 1)" :name="item.name" :key="item.name">
              <el-form-item label="子女账号" class="edit-from-width">
                <el-input v-model.trim="item.student_number" placeholder="你家小孩的登录账号" autocomplete="off" clearable
                  :maxlength="parseInt(16)" @blur="check_user(index)" @clear="childClear(index)">
                </el-input>
              </el-form-item>
              <el-form-item label="子女密码" class="edit-from-width">
                <el-input v-model.trim="item.student_password" type="password" @blur="check_user(index)"
                  placeholder="你家小孩的账号密码" autocomplete="off" :maxlength="parseInt(16)" clearable>
                </el-input>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <div v-if="isTeacher">
        <p class="form-title">角色设定（教师）</p>
        <div class="character-box">
          <!-- :class="teacher_bind.length < 10 ? 'tabs-head-title' : ''" -->
          <el-tabs v-model="teachEditTabsValue" type="card" editable @edit="teachHandleTabsEdit"
            :class="(teacher_bind.length > 0 && teacher_bind[0].teacher_class_id == '' && teacher_bind.length == 1) ? 'tabs-close' : ''">
            <el-tab-pane v-for="(item, index) in teacher_bind"
              :label="item.teacher_class_id.length > 0 ? changeTeachName(item.teacher_class_id) : '班级' + (index + 1)"
              :name="item.name" :key="item.name">
              <el-form-item label="任教班级" class="edit-from-width">
                <el-cascader :options="teachOptions" @change="teachSelect" v-model="item.teacher_class_id"
                  placeholder="选择任教班级" clearable></el-cascader>
              </el-form-item>
              <el-form-item label="班级岗位" class="edit-from-width">
                <el-select v-model="item.teacher_job_id" multiple placeholder="选择教师岗位" filterable>
                  <el-option v-for="val in teachPostData" :key="val.job_id" :label="val.job_name" :value="val.job_id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <div v-if="isStudent">
        <p class="form-title">角色设定（学生）</p>
        <el-form-item label="绑定班级" class="edit-from-width">
          <el-cascader :options="studentOptions" @change="studentSelect" v-model="studentSelectOptions"
            placeholder="暂不绑定" clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="岗位设置" class="edit-from-width">
          <el-select v-model="student_job_id" filterable placeholder="暂不指定" clearable>
            <el-option v-for="item in postData" :key="item.job_id" :label="item.job_name" :value="item.job_id">
            </el-option>
          </el-select>
        </el-form-item>
      </div>

      <p class="form-title">联系信息</p>
      <el-form-item label="用户邮箱" prop="email" class="edit-from-width">
        <el-input v-model="addForm.email" placeholder="请输入绑定邮箱" clearable></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="telphone" :rules="[
        { pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$|^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/, message: '手机号码格式错误', trigger: ['blur', 'change'] }
      ]" class="edit-from-width">
        <el-input v-model="addForm.telphone" placeholder="请输入11位手机号" autocomplete="off" :maxlength="parseInt(11)"
          clearable>
        </el-input>
      </el-form-item>
      <p class="form-title">安全验证</p>
      <el-form-item label="验证密码" prop="user_password" class="edit-from-width">
        <el-input v-model="addForm.user_password" show-password type="password" placeholder="输入当前密码进行安全认证"
          autocomplete="off" :maxlength="parseInt(16)" clearable >
        </el-input>
      </el-form-item>
      <el-form-item class="btn-item">
        <el-button size="medium" @click="cancel">取消</el-button>
        <el-button type="primary" size="medium" @click="addUser">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import uploadImg from '../../common/uploader-image.vue'
export default {
  components: {
    uploadImg
  },
  data() {
    let validatePass2 = (rule, value, callback) => {
      if (
        (this.confirmPwd || this.addForm.password) &&
        this.confirmPwd !== this.addForm.password
      ) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    let validatePwdRole = (rule, value, callback) => {
      if (value) {
        // 当前用户为管理员
        // 密码长度不得少于8位，由数字、大&小写字母、符号组成（至少4选3）
        let regManager = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d|.*[^\w\s])(?=.*[^\w\s])[^\s]{8,}$|^(?=.*[A-Z])(?=.*[a-z])(?=.*[^\w\s])(?=.*\d)[^\s]{8,}$|^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^\s]{8,}$|^(?=.*[a-z])(?=.*\d)(?=.*[^\w\s])[^\s]{8,}$|^(?=.*[A-Z])(?=.*\d)(?=.*[^\w\s])[^\s]{8,}$/;
        // 密码长度不得少于8位，由任意数字、字母组合组成
        let regx = /^(?=.*[A-Za-z])(?=.*\d)(?!.*\s)[A-Za-z\d￥!@#$%^&*()_+={}\[\]:;"'<>,.?/~`-]{8,}$/;
        if (this.isManageFlag) {
          if (!regManager.test(value)) {
            callback(new Error("密码不符合规范，密码长度不得少于8位，由数字、大写字母、小写字母、符号组成（至少4选3）"));
          } else {
            callback();
          }
        } else {
          if (!regx.test(value)) {
            callback(new Error("密码不符合规范，密码长度不得少于8位，由任意数字、字母组合组成"));
          } else {
            callback();
          }
        }
      } else {
        callback();
      }


    };
    let validateArray = (rule, value, callback) => {
      if (value && value.length <= 0) {
        callback(new Error("请至少选择一个用户角色"));
      } else {
        callback();
      }
    };
    return {
      isManageFlag: false,//判断当前勾选的角色是否具有管理员权限
      isClick: false,
      isStudent: false, // 角色权限是否为学生
      isTeacher: false, //角色权限是否为教师
      isParent: false, //角色权限是否为家长
      parentTabIndex: 1,
      teachTabIndex: 1, // tab 数量
      parentEditTabsValue: "1", // 家长可编辑的标签值
      teachEditTabsValue: "1",
      user_time: "1",
      short_time: "",
      student_job_id: "",
      confirmPwd: undefined,
      parentFlag: [], // 子女账号是否错误
      roleData: [],
      orgData: [],
      subjectData: [], // 科目
      teachClassData: [], // 教师班级
      teachPostData: [], // 教师岗位
      classData: [], // 学生班级
      postData: [], // 学生岗位
      studentData: [],
      isShowSubjectFlag: false, // 是否显示任教科目
      teacher_bind: [], // 绑定老师的班级信息
      studentSelectOptions: [],
      studentOptions: [],
      teachOptions: [],
      loading: {
        status: false,
        txt: "获取数据...",
      },
      roleParam: { type: 1 },
      orgParam: {
        data_type: "manage_tree",
        status: [1, 2],
      },
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() < parseInt(Date.now() - 8.64e7);
        },
      },
      addForm: {
        face_path: '',
        name: "",
        sex: "1",
        org_id: "",
        number: "",
        subject_id: "",
        student_bind: [],
        email: "",
        telphone: "",
        user_password: "",
        password: undefined,
        use_start_time: "",
        use_end_time: "",
        role_id: [],
        parent_bind: [],
        teacher_bind: [],
      },
      uploadOptions: {
        target: this.BASE_URL + '/api/resource/res_upload',
        testChunks: false,
        headers: { Authorization: `Bearer ` + this.$g.access_token },
      },
      rules: {
        name: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
        user_password: [
          {
            required: true,
            message: "请输入当前密码进行安全认证",
            trigger: "blur",
          },
        ],
        number: [
          {
            pattern: this.rules.account.reg,
            message: this.rules.account.msg,
            trigger: "blur",
          },
          { required: true, message: "请输入登录账号", trigger: "blur" },
        ],
        password: [
          { validator: validatePwdRole, trigger: "blur" }
        ],
        confirmPwd: [
          { validator: validatePass2, trigger: "blur" },
          {
            pattern: this.rules.strongPwd.reg,
            message: this.rules.strongPwd.msg,
            trigger: "blur",
          },
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        role_id: [
          {
            type: "array",
            validator: validateArray,
            trigger: "change",
            required: true,
          },
        ],
        user_time: [{ validator: this.valUserTime, trigger: "change" }],
      },
    };
  },
  created() {
    this.getRoleData();
    this.getSubjectData();
    this.getOrgData();
  },
  methods: {
    getImg(mess) {
      this.addForm.face_path = mess.file_path;
    },
    valUserTime(rule, value, callback) {
      if (this.user_time === "2" && this.short_time == "") {
        callback(new Error("请输入使用截止时间"));
      } else {
        callback();
      }
    },
    changeTeachName(val) {
      let name = "";

      this.teachOptions.forEach((item) => {
        if (val[0] && item.value == val[0]) {
          name = item.label;

          if (val[1]) {
            item.children.forEach((res) => {
              if (val[1] == res.value) {
                name = item.label + "/" + res.label;

                if (val[2]) {
                  res.children.forEach((data) => {
                    if (data.value == val[2]) {
                      name = item.label + "/" + res.label + "/" + data.label;
                    }
                  });
                }
              }
            });
          }
        }
      });

      return name;
    },
    // 清空子女账号时清空密码
    childClear(index) {
      let data = this.addForm.parent_bind[index];

      if (data.student_number == "" && data.student_password != "") {
        this.addForm.parent_bind[index].student_password = "";
        this.addForm.parent_bind[index].childrenName = "";
      }
    },
    check_user(index) {
      let data = this.addForm.parent_bind[index];

      if (data.student_number != "" && data.student_password != "") {
        let params = {
          number: data.student_number,
          password: data.student_password,
        };
        let success = (res) => {
          this.$message.success("子女账号密码正确");
          this.addForm.parent_bind[index].childrenName = res.data.name;
        };
        let fail = (res) => {
          this.$message.error(res.msg);
          data.student_password = "";
        };

        this.$ajax.get("api/user/check_user", {
          params: params,
          func: { success: success, fail: fail },
        });
      }
    },
    isShowSubject() {
      this.isShowSubjectFlag =
        this.addForm.role_id.indexOf(this.$g.TEACHER_ROLE_ID) > -1;
    },
    teachSelect(val) {
      // 动态改变标签的名字
      let len = this.teachEditTabsValue;
      this.teachPostData = [];
      this.teacher_bind.forEach((item) => {
        if (item.name == len) {
          item.teacher_job_id = [];
        }
      });

      if (val.length === 3) {
        let flag = false;

        this.teacher_bind.forEach((item) => {
          if (item.name == len) {
            item.teacher_class_id = [];
          }
        });

        this.teacher_bind.forEach((item) => {
          if (val[2] === item.teacher_class_id[2]) {
            flag = true;
          }
        });

        if (flag) {
          this.teacher_bind.forEach((item) => {
            if (item.name == len) {
              item.teacher_class_id = [];
            }
          });

          this.$message.warning("不可以重复选中任教班级");
        } else {
          this.teacher_bind.forEach((item) => {
            if (item.name == len) {
              item.teacher_class_id = val;
            }
          });

          this.getTeachPost(val[2]);
        }
      }

      if (val.length < 3) {
        this.teacher_bind.forEach((item) => {
          if (item.name == len) {
            item.teacher_class_id = [];
          }
        });
      }
    },
    /**
     * 获取教师岗位信息
     * @param {Number} classId 班级 id
     */
    getTeachPost(classId) {
      let params = {
        class_id: classId,
      };
      const success = (res) => {
        this.teachPostData = res.data.teacher_job;
      };

      this.$ajax.get("api/user/class_job_data", {
        params: params,
        func: { success: success },
      });
    },
    // 获取学生岗位信息
    studentSelect(val) {
      this.postData = [];
      this.student_job_id = "";

      if (val.length === 3) {
        let params = {
          class_id: val[2],
        };
        const success = (res) => {
          // 每个班别的岗位不一样，不能用同一个数组
          this.postData = res.data.student_job;
        };
        this.$ajax.get("api/user/class_job_data", {
          params: params,
          func: { success: success },
        });
      }

      if (this.studentSelectOptions.length < 3) {
        this.studentSelectOptions = [];
      }
    },
    // 从组织架构获取班级信息
    studentItem() {
      let data = this.studentData[0].children;
      if (data) {
        data.forEach((val, index) => {
          let data2 = val.children;

          if (!is_empty(data2)) {
            this.studentOptions.push({
              value: val.id,
              label: val.name,
              children: [],
            });

            data2.forEach((res, index2) => {
              let data3 = res.children;

              if (!is_empty(data3)) {
                this.studentOptions[index].children.push({
                  value: res.id,
                  label: res.name,
                  children: [],
                });

                data3.forEach((tex, index3) => {
                  this.studentOptions[index].children[index2].children.push({
                    value: tex.id,
                    label: tex.name,
                  });
                });
              } else {
                this.studentOptions[index].children.push({
                  value: res.id,
                  label: res.name,
                });
              }
            });
          } else {
            this.studentOptions.push({
              value: val.id,
              label: val.name,
            });
          }
        });
      }
      this.teachOptions = deep_clone(this.studentOptions);
    },
    parentHandleTabsEdit(targetName, action) {
      if (action === "add") {
        let newTabName = ++this.parentTabIndex + "";
        this.addForm.parent_bind.push({
          name: newTabName,
          student_number: "",
          student_password: "",
          childrenName: "",
        });
        this.parentEditTabsValue = newTabName;
      }

      if (this.addForm.parent_bind.length > 1) {
        if (action === "remove") {
          let tabs = this.addForm.parent_bind;
          let activeName = this.parentEditTabsValue;

          if (activeName === targetName) {
            tabs.forEach((tab, index) => {
              if (tab.name === targetName) {
                let nextTab = tabs[index + 1] || tabs[index - 1];
                if (nextTab) {
                  activeName = nextTab.name;
                }
              }
            });
          }

          this.parentEditTabsValue = activeName;
          this.addForm.parent_bind = tabs.filter(
            (tab) => tab.name !== targetName
          );
        }
      } else {
        if (action === "remove") {
          this.addForm.parent_bind[0].student_flag = null;
          this.addForm.parent_bind[0].student_number = "";
          this.addForm.parent_bind[0].student_password = "";
          this.addForm.parent_bind[0].childrenName = "";
        }
      }
    },
    teachHandleTabsEdit(targetName, action) {
      if (action === "add") {
        let newTabName = ++this.teachTabIndex + "";
        this.teacher_bind.push({
          name: newTabName,
          teacher_class_id: [],
          teacher_job_id: [],
        });
        this.teachEditTabsValue = newTabName;
      }
      if (this.teacher_bind.length > 1) {
        if (action === "remove") {
          let tabs = this.teacher_bind;
          let activeName = this.teachEditTabsValue;

          if (activeName === targetName) {
            tabs.forEach((tab, index) => {
              if (tab.name === targetName) {
                let nextTab = tabs[index + 1] || tabs[index - 1];
                if (nextTab) {
                  activeName = nextTab.name;
                }
              }
            });
          }

          this.teachEditTabsValue = activeName;
          this.teacher_bind = tabs.filter((tab) => tab.name !== targetName);
        }
      } else {
        if (action === "remove") {
          this.teacher_bind[0].teacher_job_id = [];
          this.teacher_bind[0].teacher_class_id = [];
        }
      }
    },
    getOrgData() {
      if (this.$store.state.checkLevel) {
        this.orgParam.direction = "down";
        this.orgParam.data_type = "manage_tree";
        this.orgParam.pid = 1;
      }
      // 重写成功回调
      let success = (data) => {
        this.orgData = data.data;
        this.studentData = data.data;
        this.addForm.org_id = this.orgData[0].id;
        this.$forceUpdate(); //强制渲染
        this.studentItem();
      };
      if (this.$store.state.checkLevel) {
        this.$ajax.get("api/newlevel/platform_org", {
          params: this.orgParam,
          func: { success: success },
        });
      } else {
        this.$ajax.get("api/org/org", {
          params: this.orgParam,
          func: { success: success },
        });
      }
    },
    getRoleData() {
      // 1.教育局默认角色：后台管理员/教师/学生/家长/游客
      // 2.学校默认角色： 后台管理员/教研员/游客
      this.loading.status = true;

      // 重写成功回调
      let success = (data) => {
        this.loading.status = false;
        this.roleData = data.data;

        this.addForm.parent_bind = [
          {
            name: "1",
            student_number: "",
            student_password: "",
            childrenName: "",
          },
        ];
        this.teacher_bind = [
          {
            name: "1",
            teacher_class_id: [],
            teacher_job_id: [],
          },
        ];
      };
      let fail = (data) => {
        this.loading.status = false;
        this.$message.error(data.msg);
      };

      this.$ajax.get("api/user/user_allow_control", {
        params: this.roleParam,
        func: { success: success, fail: fail },
      });
    },
    getSubjectData() {
      // 获取科目信息
      let success = (data) => {
        this.subjectData = data.data;
      };
      if (this.$store.state.checkLevel) {
        this.$ajax.get("api/newlevel/platform_subject", {
          params: {},
          func: { success: success },
        });
      } else {
        this.$ajax.get("api/cate/simple_subject", {
          params: {},
          func: { success: success },
        });
      }
    },
    /**
     * 不同角色权限的交集
     */
    addFormRoleChange(val) {
      if (val.length === 0) {
        this.isTeacher = false;
        this.isStudent = false;
        this.isParent = false;
        return false;
      }

      let curRoleId = parseInt(val[val.length - 1]);
      switch (curRoleId) {
        case 1:
        case 2:
        case 3: // 管理员与学生和游客角色无交集
          if (val.length > 1) {
            this.addForm.role_id = val.filter((item) => {
              return item !== 7 && item !== 4;
            });
          }
          break;
        case 4: // 只与自建角色有交集
          if (val.length > 1) {
            this.addForm.role_id = val.filter((item) => {
              return item === 4 || item >= 9;
            });
          }
          break;
        case 5: // 家长与管理员、教师、自建角色有交集
          if (val.length > 1) {
            this.addForm.role_id = val.filter((item) => {
              return item <= 3 || item === 5 || item === 6 || item >= 9;
            });
          }
          break;
        case 6: // 教师与管理员、家长、自建角色有交集
          if (val.length > 1) {
            this.addForm.role_id = val.filter((item) => {
              return item <= 3 || item === 5 || item === 6 || item >= 9;
            });
          }
          break;
        case 7: // 游客跟其他角色互斥
          this.addForm.role_id = [curRoleId];
          break;
        case 8: // 教研员跟管理员和自建角色有交集，与其他角色无交集
          if (val.length > 1) {
            this.addForm.role_id = val.filter((item) => {
              return item <= 3 || item >= 8;
            });
          }
          break;
        default:
          // 自建角色与游客无交集
          if (val.length > 1) {
            this.addForm.role_id = val.filter((item) => {
              return item !== 7;
            });
          }
      }

      this.isStudent = this.addForm.role_id.includes(4);
      this.isParent = this.addForm.role_id.includes(5);
      this.isTeacher = this.addForm.role_id.includes(6);
      this.isShowSubject();

      // if( this.$g.STUDENT_ROLE_ID === curRoleId || curRoleId >= 7  ){
      //     this.addForm.role_id = [curRoleId];
      //     this.isTeacher = false;
      //     this.isParent = false;

      //     if (this.$g.STUDENT_ROLE_ID === curRoleId) {
      //         this.isStudent = true;
      //     } else {
      //         this.isStudent = false;
      //     }
      // }else{
      //     let teacherIn = false;
      //     let parentIn = false;

      //     for ( let i = val.length - 1; i >= 0; i-- ) {
      //         let roleIdInx = parseInt(val[i]);
      //         if( this.$g.STUDENT_ROLE_ID === roleIdInx || roleIdInx >= 7){
      //             this.addForm.role_id.splice(i,1);
      //         }

      //         if (this.$g.STUDENT_ROLE_ID === curRoleId) {
      //             this.isStudent = true;
      //         } else {
      //             this.isStudent = false;
      //         }
      //         if( this.$g.TEACHER_ROLE_ID === roleIdInx ){
      //             teacherIn = true;
      //         }
      //         if( this.$g.PARENT_ROLE_ID === roleIdInx ){
      //             parentIn = true;
      //         }
      //     }

      //     if( teacherIn ){
      //         this.isTeacher = true;
      //     }else{
      //         this.isTeacher = false;
      //     }
      //     if( parentIn ){
      //         this.isParent = true;
      //     }else{
      //         this.isParent = false;
      //     }
      // }
      // 判断当前勾选的角色是否具有管理员权限
      this.getManagerFalg()
    },
    getManagerFalg() {
      let success = (res) => {
        // 处理后端返回的数据
        this.isManageFlag = res.data == true ? true : false;
        if (this.addForm.password) {
          this.$refs.addForm.validateField('password');
        }
      }
      let params = {
        role_id: this.addForm.role_id
      }
      this.$ajax.get("api/user/checkManager", {
        params,
        func: { success },
      });
    },
    // 确定按钮点击事件-表单验证
    addUser() {
      if (!this.isClick) {
        if (this.parentFlag.length > 0) {
          this.$message.error("子女账号不正确");
          return;
        }

        this.$refs["addForm"].validate((valid) => {
          if (valid) {
            this.isClick = true;
            this.checkUser();
          }
        });
      }
    },
    // 检查验证码是否正确
    checkUser() {
      const success = (res) => {
        this.submit();
        // this.$message.success(res.msg);
      };
      const fail = (res) => {
        this.$message.error(res.msg);
        this.isClick = false;
      };
      const checkParams = {
        id: this.$g.user_id,
        password: this.addForm.user_password,
      };
      this.$ajax.get("api/user/check_user_by_id", {
        params: checkParams,
        func: { success, fail },
      });
    },
    //验证通过后，提交表单数据
    submit() {
      let success = (data) => {
        this.$message.success(data.msg);
        this.isClick = false;
        this.cancel();
      };
      let fail = (data) => {
        this.$message.error(data.msg);
        this.isClick = false;
      };

      this.addForm.org_id = 1;
      // 学生角色选中班级
      if (this.studentSelectOptions.length === 3) {
        this.addForm.student_bind = [];
        this.addForm.student_bind.push({
          student_class_id: this.studentSelectOptions[2],
          student_job_id: this.student_job_id,
        });
      } else {
        this.addForm.student_bind = [];
      }

      // 老师角色选中班级
      let teacher_demo = [];
      this.teacher_bind.forEach((item) => {
        if (item.teacher_class_id.length === 3) {
          teacher_demo.push({
            teacher_class_id: item.teacher_class_id[2],
            teacher_job_id: item.teacher_job_id,
          });
        }
      });
      this.addForm.teacher_bind = teacher_demo;

      // 家长角色选中子女
      let parent_demo = [];
      this.addForm.parent_bind.forEach((item) => {
        if (item.student_number != "" && item.student_password != "") {
          parent_demo.push({
            student_number: item.student_number,
            student_password: item.student_password,
          });
        }
      });
      this.addForm.parent_bind = parent_demo;

      let new_time = "00-00-00 00:00:00";
      this.addForm.use_start_time = new_time;
      this.addForm.use_end_time =
        this.user_time === "1" ? new_time : this.short_time;

      // 角色权限：提交数据，role_id实际是要id，模板checkbox绑定的是base_id，所以此处需要转一下，拿到id
      let idArr = [];
      this.roleData.map((x) => {
        if (this.addForm.role_id.includes(x.base_id === 0 ? x.id : x.base_id)) {
          idArr.push(x.id);
        }
      });
      this.addForm.role_id = idArr;

      this.$ajax.post("api/user/user", this.addForm, {
        func: { success: success, fail: fail },
      });
    },
    cancel() {
      this.$refs["addForm"].resetFields();
      this.$router.push("/user/user/platform-user/");
    },
  },
};
</script>

<style lang="scss">
.platform-user-add {
  .el-form-item__error {
    width: 550px;
  }

  .edit-from-width {
    width: 400px;
  }

  .tabs-head-title {
    .el-tabs__header {
      display: inline-block;
    }
  }

  .el-tabs__header {
    display: inline-block;
  }

  .tabs-close {
    .el-icon-close {
      visibility: hidden;
      transition: none;
    }
  }

  .add-form {
    padding-left: 30px;
    max-width: 800px;

    .user-time {
      .el-form-item__content .el-radio-group {
        width: 100%;

        .el-radio {
          line-height: 2;
          width: 100%;
        }

        .el-radio:last-child {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          margin-left: 0;
        }
      }
    }

    .form-title {
      border-left: 5px solid #4cc3c3;
      margin-left: -20px;
      padding-left: 7px;
      text-align: left;
    }

    .el-form-item__content {
      margin-left: 100px !important;
    }

    .el-checkbox.is-bordered+.el-checkbox.is-bordered {
      margin-left: 0;
    }

    .el-checkbox-group {
      label {
        margin-right: 15px;
      }
    }

    .btn-item {
      margin-top: 35px;
      text-align: center;

      .el-form-item__content {
        margin-left: 0 !important;
        padding-top: 20px;
        border-top: 1px dotted #ccc;
      }
    }
  }
}

.avatar-uploader .el-upload {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 120px;
  display: block;
}
</style>
